package com.base.data.elasticsearch.repository.support;

import com.base.data.elasticsearch.core.mapping.BaseElasticsearchPersistentEntity;
import com.base.data.elasticsearch.core.mapping.BaseElasticsearchPersistentProperty;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.util.Assert;

public class BaseElasticsearchEntityInformationCreatorImpl implements BaseElasticsearchEntityInformationCreator {

    private final MappingContext<? extends BaseElasticsearchPersistentEntity<?>, BaseElasticsearchPersistentProperty> mappingContext;

    public BaseElasticsearchEntityInformationCreatorImpl(
            MappingContext<? extends BaseElasticsearchPersistentEntity<?>, BaseElasticsearchPersistentProperty> mappingContext) {

        Assert.notNull(mappingContext, "MappingContext must not be null!");

        this.mappingContext = mappingContext;
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T, ID> BaseElasticsearchEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {

        BaseElasticsearchPersistentEntity<T> persistentEntity = (BaseElasticsearchPersistentEntity<T>) mappingContext
                .getRequiredPersistentEntity(domainClass);

        Assert.notNull(persistentEntity, String.format("Unable to obtain mapping metadata for %s!", domainClass));
        Assert.notNull(persistentEntity.getIdProperty(), String.format("No id property found for %s!", domainClass));

        return new BaseMappingElasticsearchEntityInformation<T, ID>(persistentEntity);
    }
}
